package com.cocotingo.lab.snail.previewer;

import java.awt.Color;
import java.awt.Container;
import java.io.FileInputStream;

import org.eclipse.core.resources.IFile;

import com.cocotingo.snail.View;
import com.cocotingo.snail.ViewContext;
import com.cocotingo.snail.template.EventHandler;
import com.cocotingo.snail.template.TemplateView;
import com.cocotingo.snail.template.previewer.TemplatePreviewer;
import com.cocotingo.snail.template.previewer.TemplatePreviewerView;

public class Context extends ViewContext implements EventHandler {
	
	private final PreviewerView delegate;
	private TemplatePreviewer loader = null;
	private TemplatePreviewerView targetView = null;

	public Context(Container container, PreviewerView delegate) {
		super(container, new TemplateView() {
			{
				setBackgroundColor(Color.white);
			}
		});
		this.delegate = delegate;
		((TemplateView) getRootView()).addEventHandler(EventHandler.Layout, this);
	}
	
	public void displayTemplate(IFile file) {
		loader = new TemplatePreviewer(getGraphicsConfiguration());
		try {
			loader.load(new FileInputStream(file.getLocation().toFile()));
		} catch (Exception e) {
			// TODO: display error
			loader = null;
			resetTargetView(null);
			return;
		}
		String[] ids = loader.getAllTemplateIDs();
		if (ids.length > 0) {
			displayTemplate(ids[0]);
		} else {
			// TODO: display error
		}
	}
	
	public void displayTemplate(String id) {
		if (loader != null) {
			try {
				TemplatePreviewerView view = loader.makeView(id);
				resetTargetView(view);
			} catch (Exception e) {
				// TODO: display error
				resetTargetView(null);
			}
		}
	}
	
	private void resetTargetView(TemplatePreviewerView view) {
		if (targetView != null) {
			targetView.removeEventHandler(TemplatePreviewerView.SelectedViewChanged, this);
			targetView.removeFromSuperView();
		}
		targetView = view;
		if (targetView != null) {
			getRootView().addSubview(targetView);
			targetView.addEventHandler(TemplatePreviewerView.SelectedViewChanged, this);
			TemplateView rootView = (TemplateView) getRootView();
			rootView.layout();
		}
	}

	@Override
	public void handle(TemplateView sender, String eventName, Object arg) {
		if (eventName.equals(TemplatePreviewerView.SelectedViewChanged)) {
			delegate.showDetailOfView(targetView.getSelecteView());
		} else if (eventName.equals(EventHandler.Layout)) {
			if (targetView != null) {
				View.scaleViewWithMarginToSuperView(targetView, 30);
			}
		}
	}

}
